package server

import (
	"encoding/json"
	"errors"
	"github.com/nsqio/go-nsq"
	"server/base"
	message2 "server/common/models/message"
	"server/common/utils"
	"server/pkg/log"
	nsq2 "server/pkg/nsq"
	"server/pkg/websocket"
)

type UserMessage struct {
}

func (u UserMessage) GetTopic() string {
	return string(nsq2.TOPIC_USER_MESSAGE)
}

func (u UserMessage) GetChannel() string {
	return string(nsq2.TOPIC_USER_MESSAGE)
}

func (u UserMessage) GetHandler() func(message *nsq.Message) error {
	return func(message *nsq.Message) error {
		var userMessage message2.UserMessage
		err := json.Unmarshal(message.Body, &userMessage)
		if err != nil {
			log.Error("[UserMessage]", err, string(message.Body))
			return nil
		}

		base.Mysql.Create(&userMessage)
		if userMessage.Id == 0 {
			log.Error("[UserMessage]", errors.New("消息发送失败"), string(message.Body))
		}

		base.App.WebSocketHub.SendToUser(utils.UserIdToSocketId(userMessage.To), websocket.Message{
			Type: "user_message", Data: userMessage,
		})
		return nil
	}
}
